package controllers;

import models.cms.*;
import play.data.Upload;
import play.mvc.With;
import ret.Ret;
import swagger.annotations.ApiInfo;
import swagger.annotations.Param;
import utils.NeedLogin;
import utils.ResourceUtils;
import utils.SessionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@ApiInfo(desc = "互动模块")
@With(LoginFilter.class)
public class Forum extends SController {

    @ApiInfo(desc = "根据输入的主题实时搜索相关主题")
    public static void suggest_by_title(@Param(name = "title") String title) {
        renderJSON(Ret.ok());
    }

    @ApiInfo(desc = "保存")
    @NeedLogin
    public static void save_post(
            @Param(name = "id", in = "formData") long id,
            @Param(name = "subject", in = "formData") String subject,
            @Param(name = "summary", in = "formData") String summary,
            @Param(name = "content", in = "formData") String content,
            @Param(name = "board_id", in = "formData") long board_id,
            @Param(name = "state", in = "formData") int state,
            @Param(name = "attaches", in = "formData", desc = "提交附件id，允许多个") Long[] attaches,
            @Param(name = "main_images", in = "formData", desc = "提交附件id，允许多个") Long[] main_images
    ) {

        Post p = null;
        if (id > -1) {
            p = Post.findById(id);
            if (p == null) {
                renderJSON(Ret.error("帖子不存在"));
            }
        } else {
            p = new Post();
        }
        p.state = state;
        p.subject = subject;
        p.content = content;
        p.summary = summary;

        if (attaches != null && attaches.length > 0) {
            p.resources = new ArrayList<Resource>();
            final Post finalP = p;
            Arrays.stream(attaches).forEach(sid -> {
                finalP.resources.add(Resource.findById(sid));
            });
        }
//        if (main_images != null && main_images.length > 0) {
//            p.main_images = new ArrayList<Resource>();
//            final Post finalP = p;
//            Arrays.stream(main_images).forEach(sid -> {
//                finalP.main_images.add(Resource.findById(sid));
//            });
//        }
        p.user = SessionUtils.getCurrentUser();
        p.created_at = new Date();
        p.save();
        if (request.isAjax()) {
            renderJSON(Ret.ok().data("post", p));
        } else {
            F.view_post(p.getId());
        }
    }

    @ApiInfo(desc = "保存")
    @NeedLogin
    public static void save_post_multi_part(
            @Param(name = "id", in = "formData") long id,
            @Param(name = "subject", in = "formData") String subject,
            @Param(name = "summary", in = "formData") String summary,
            @Param(name = "content", in = "formData") String content,
            @Param(name = "board_id", in = "formData") long board_id,
            @Param(name = "state", in = "formData") int state,
            @Param(name = "attaches", in = "formData", desc = "多个文件") Upload[] attaches) {

        Post p = null;
        if (id > -1) {
            p = Post.findById(id);
            if (p == null) {
                renderJSON(Ret.error("帖子不存在"));
            }
        } else {
            p = new Post();
        }
        p.state = state;
        p.subject = subject;
        p.content = content;
        p.summary = summary;
        if (attaches != null && attaches.length > 0) {
            p.resources = new ArrayList<Resource>();
            final Post finalP = p;
            Arrays.stream(attaches).forEach(sid -> {
                finalP.resources.add(ResourceUtils.process(sid));
            });
        }
//        if (p.resources != null && p.resources.size() > 0) {
//            p.main_images = new ArrayList<Resource>();
//            p.main_images.add(p.resources.get(0));
//        }
        p.user = SessionUtils.getCurrentUser();
        p.created_at = new Date();
        p.save();
        if (request.isAjax()) {
            renderJSON(Ret.ok().data("post", p));
        } else {
            F.view_post(p.getId());
        }
    }

    @ApiInfo(desc = "回复")
    public static void save_reply(
            @Param(name = "id", in = "formData", desc = "回复的ID") long id,
            @Param(name = "post_id", in = "formData", desc = "主贴的ID") long post_id,
            @Param(name = "reply_id", in = "formData", desc = "回复的回复，允许为空") Long reply_id,
            @Param(name = "content", in = "formData", desc = "回复内容") String content,
            @Param(name = "attachs", in = "formData", desc = "附件的ID，允许多个") Long[] attachs) {
        Post post = Post.findById(post_id);
        Post reply = id > 0 ? Post.findById(id) : new Post();
        reply.to_post = post;
        reply.content = content;
        reply.user = SessionUtils.getCurrentUser();
        reply.created_at = new Date();
        if (attachs != null && attachs.length > 0) {
            reply.resources = new ArrayList<Resource>();
            Arrays.stream(attachs).forEach(rid -> {
                reply.resources.add(Resource.findById(rid));
            });
        }
        if (reply_id != null && reply_id > -1) {
            reply.to_post = Post.findById(reply_id);
        }
        reply.save();
        post.cnt_reply = post.cnt_reply + 1;
        post.save();
        if (request.isAjax()) {
            renderJSON(Ret.ok().data("reply", reply));
        } else {
            F.view_post(post.getId());
        }
    }

    @ApiInfo(desc = "回复")
    public static void save_reply_multi_part(
            @Param(name = "id", in = "formData", desc = "回复的ID") long id,
            @Param(name = "post_id", in = "formData", desc = "主贴的ID") long post_id,
            @Param(name = "reply_id", in = "formData", desc = "回复的回复，允许为空") Long reply_id,
            @Param(name = "content", in = "formData", desc = "回复内容") String content,
            @Param(name = "attachs", in = "formData", desc = "附件的") Upload[] attachs) {
        Post post = Post.findById(post_id);
        Post reply = id > 0 ? Post.findById(id) : new Post();
        reply.to_post = post;
        reply.content = content;
        reply.user = SessionUtils.getCurrentUser();
        reply.created_at = new Date();
        if (attachs != null && attachs.length > 0) {
            reply.resources = new ArrayList<Resource>();
            Arrays.stream(attachs).forEach(rid -> {
                reply.resources.add(ResourceUtils.process(rid));
            });
        }
        if (reply_id != null && reply_id > -1) {
//            reply.to_reply = Post.findById(reply_id);
        }
        reply.save();
        post.cnt_reply = post.cnt_reply + 1;
        post.save();
        if (request.isAjax()) {
            renderJSON(Ret.ok().data("reply", reply));
        } else {
            F.view_post(post.getId());
        }
    }


    public static void delete_post(long id) {
        Post post = Post.findById(id);
//        post.state = Post.STATE_DELETED;
        post.save();
        renderJSON(Ret.ok().data("post", post));
    }



    @ApiInfo(desc = "根据分类加载帖子")
    public static void list_posts(
            @Param(name = "board_id", in = "formData", desc = "分类id") long board_id,
            @Param(name = "from", in = "formData", desc = "从第几个开始加载，包含") int from,
            @Param(name = "to", in = "formData", desc = "需要加载几条") int to) {
        renderJSON(Ret.ok()
                .data("posts",
                        Post.find("board_id = ?", board_id).from(from)
                        .fetch(to - from)));
    }

   

    public static void voteup(Long post_id) {
        Post post = Post.findById(post_id);
        post.save();
        renderJSON(post);
    }

    public static void follow(Long post_id) {
        Post post = Post.findById(post_id);
        post.save();
        renderJSON(post);
    }

    public static void favor(Long post_id) {
        Post post = Post.findById(post_id);
        Favor f = new Favor();
        f.user = SessionUtils.getCurrentUser();
        f.post = post;
        f.save();
        post.save();
        renderJSON(Ret.ok().data("post", post));
    }

    public static void my_favors() {
        List<Post> posts = Post.find("select p from models.cms.Post p where exists (select f from models.cms.Favor f where f.post = p and f.user = ?)", SessionUtils.getCurrentUser()).fetch(20);
        renderJSON(Ret.ok().data("posts", posts));
    }

    public static void my_follows() {
        List<Post> posts = Post.find("select p from models.cms.Post p where exists (select f from models.cms.Follow f where f.post = p and f.user = ?)", SessionUtils.getCurrentUser()).fetch(20);
        renderJSON(Ret.ok().data("posts", posts));
    }

    public static void my_drafts() {
        List<Post> posts = Post.find("user = ? and state = ? and state != 9 order by created_at desc", SessionUtils.getCurrentUser(), Post.STATE_DRAFT).fetch(20);
        renderJSON(Ret.ok().data("posts", posts));
    }

    public static void get_post(long post_id) {
        Post post = Post.findById(post_id);
        post.save();
        renderJSON(Ret.ok().data("post", post));
    }


    @NeedLogin
    public static void new_post() {
        render();
    }

    @NeedLogin
    public static void edit_post(long id) {
        Post post = Post.findById(id);
        render("Forum/new_post.html", post);
    }

    public static void view_post(long id) {
        Post post = Post.findById(id);
        post.save();
        render(post);
    }

    public static void index(int from, int state) {
        List<Post> posts = Post.find("(? = -1 or state = ?) order by created_at desc", state, state).from(from).fetch(10);
        long total = Post.count("(? = -1 or state = ?) ", state, state);
        render(posts, total, from, state);
    }



    public static void hotest() {
        List<Post> posts = Post.find("state != 9 order by view_cnt desc").fetch(20);
        renderJSON(Ret.ok().data("posts", posts));
    }

    public static void newest() {
        List<Post> posts = Post.find("state != 9 order by created_at desc").fetch(20);
        renderJSON(Ret.ok().data("posts", posts));
    }

    public static void excellent() {
        List<Post> posts = Post.find("state != 9 order by voteup_cnt desc").fetch(20);
        renderJSON(Ret.ok().data("posts", posts));
    }

}
